<template>
  <div class="investigator-container">
    <div style="text-align: start">
      <a-button @click="add" v-auth="'expense:schadd'">新建日程</a-button>
    </div>
    <a-table
      :loading="loading"
      :columns="columns"
      :data-source="dataSource"
      rowKey="id"
      :pagination="false"
      style="height: 700px; margin-top: 20px; overflow: hidden"
    >
      <div slot="action" slot-scope="text, record">
        <a
          @click="edit(record)"
          style="margin-right: 8px"
          v-auth="'expense:schupdate'"
        >
          编辑
        </a>
        <a-divider type="vertical" />

        <a style="margin-right: 8px" @click="editReport(record)"> 填报 </a>
        <a-divider type="vertical" />

        <a-popconfirm
          title="确定删除吗?"
          @confirm="deleteSchedule(record)"
          ok-text="删除"
          cancel-text="取消"
        >
          <a style="margin-right: 8px"> 删除 </a>
        </a-popconfirm>
      </div>
    </a-table>
    <div class="pagination">
      <a-pagination
        :defaultPageSize="pagination.pageSize"
        :current="pagination.current"
        show-quick-jumper
        :total="pagination.total"
        show-less-items
        @change="onPageChange"
      />
    </div>
    <a-modal
      :confirm-loading="confirmLoading"
      :title="title"
      :visible="visible"
      :destroyOnClose="true"
      @ok="handleOk"
      @cancel="handleCancel"
      :width="800"
    >
      <a-form :form="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="日程名称">
          <a-input
            placeholder="请输入日程名称"
            v-decorator="[
              'scheName',
              {
                rules: [{ required: true, message: '请输入日程名称!' }],
                initialValue: form.scheName,
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="日程起始时间">
          <a-week-picker
            placeholder="请选择日程起始时间"
            v-decorator="[
              'beginTime',
              {
                rules: [{ required: true, message: '请选择日程起始时间!' }],
                initialValue: form.beginTime,
              },
            ]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import {
  getScheduleData,
  addSchedule,
  editSchedule,
  deleteSchedule,
} from '@/api/schedule';
import moment from 'moment';

const columns = [
  {
    title: '创建人',
    dataIndex: 'creator',
    align: 'center',
  },
  {
    title: '日程名称',
    dataIndex: 'scheName',
    align: 'center',
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' },
    align: 'center',
  },
];
export default {
  name: 'investigator',
  components: {},
  data() {
    return {
      form: this.$form.createForm(this, {
        beginTime: undefined,
        scheName: undefined,
      }),
      loading: true,
      dataSource: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      parames: {},
      columns,
      title: '新建日程',
      visible: false,
      editId: '',
      confirmLoading: false,
      type: 'add',
    };
  },
  created() {
    this.getData();
  },
  computed: {},
  methods: {
    getData() {
      this.loading = true;
      let request = { ...this.parames };
      request.currentPage = this.pagination.current;
      request.pageSize = this.pagination.pageSize;
      request.type = 0;
      getScheduleData(request).then((response) => {
        this.dataSource = response.data.list;
        this.pagination.total = response.data.count;
        this.loading = false;
      });
    },
    onPageChange(page, pageSize) {
      this.pagination.current = page;
      this.pagination.pageSize = pageSize;
      this.getData();
    },
    edit(record) {
      console.log(record.beginTime);
      this.type = 'edit';
      this.title = '编辑日程';
      this.editId = record.id;
      this.form.beginTime = moment(record.beginTime, 'YYYY-MM-DD');
      this.form.scheName = record.scheName;
      this.visible = true;
    },
    add() {
      this.type = 'add';
      this.title = '新建用户';
      this.visible = true;
    },
    handleCancel() {
      this.initForm();
      this.visible = false;
    },
    handleOk(e) {
      e.preventDefault();
      const { type } = this;
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          let request = { ...values, id: this.editId };
          request.type = 0;
          request.beginTime = this.getDate(
            this.getFirstDayOfWeek(
              new Date(values.beginTime.format('YYYY-MM-DD'))
            )
          );
          console.log(request);
          if (type === 'add') {
            addSchedule(request).then((response) => {
              console.log(response);
              if (response.code == 200) {
                this.$message.success(response.message);
                this.getData();
                this.visible = false;
              } else {
                this.$message.error(response.message);
              }
              this.confirmLoading = false;
              this.initForm();
            });
          } else {
            editSchedule(request).then((response) => {
              console.log(response);
              if (response.code == 200) {
                this.$message.success(response.message);
                this.getData();
                this.visible = false;
              } else {
                this.$message.error(response.message);
              }
              this.confirmLoading = false;
              this.initForm();
            });
          }
        }
      });
    },
    initForm() {
      Object.keys(this.form.getFieldsValue()).forEach((key) => {
        this.form[key] = undefined;
      });
    },
    getDate(datesForWeek) {
      const year = datesForWeek.getFullYear();
      const month = (datesForWeek.getMonth() + 1).toString().padStart(2, '0');
      const day = datesForWeek.getDate().toString().padStart(2, '0');
      const formattedDateString = `${year}-${month}-${day}`;
      return formattedDateString;
    },
    getFirstDayOfWeek(date) {
      var day = date.getDay() || 7;
      return new Date(
        date.getFullYear(),
        date.getMonth(),
        date.getDate() + 1 - day
      );
    },
    deleteSchedule(record) {
      deleteSchedule([record.id]).then((response) => {
        if (response.code == 200) {
          this.getData();
          this.$message.success('删除成功');
        } else {
          this.$message.error(response.message);
        }
      });
    },
    editReport(record) {
      console.log(record);
      this.$router.push({
        path: '/investigator-weekly-schedule-create',
        query: {
          id: record.id,
          name: record.scheName,
          backPath: '/leader-weekly-schedule',
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.investigator-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  .pagination {
    height: 30px;
    line-height: 30px;
    width: 100%;
    text-align: right;
  }
}
</style>
